{% extends 'game_core/base.html' %}
{% load static %}
{% load game_filters %}

{% block content %}
<div class="game-container">
    <!-- 楼层信息 -->
    <div class="floor-info">
        <h2>第 {{ session.current_floor }} 层</h2>
    </div>

    <!-- 角色状态 -->
    <div class="character-status">
        <div class="character-avatar">
            <img src="{% static 'images/character.png' %}" alt="角色">
        </div>
        <div class="status-bars">
            <div class="hp-bar">
                <div class="hp-fill" style="width: {{ session.current_hp|percentage:character.base_hp }}%"></div>
                <span>HP: {{ session.current_hp }}/{{ character.base_hp }}</span>
            </div>
        </div>
        <div class="character-stats">
            <p>攻击力: {{ character.base_attack }}</p>
            <p>防御力: {{ character.base_defense }}</p>
            <p>金币: {{ character.gold }}</p>
        </div>
    </div>

    <!-- 战斗区域 -->
    <div class="battle-area">
        <div class="monsters-container">
            {% for monster in monsters %}
            <div class="monster-container" data-monster-id="{{ monster.id }}">
                <div class="target-indicator">目标</div>
                <h3>{{ monster.name }}</h3>
                <div class="monster-image-container" title="点击查看详细信息">
                    <img src="{% static 'images/monster/'|add:monster.image %}" 
                         alt="{{ monster.name }}" 
                         onerror="this.src='{% static 'images/monster/default.png' %}'"
                         class="monster-image">
                    <div class="monster-tooltip">
                        <div class="tooltip-content">
                            <h4>{{ monster.name }}</h4>
                            <p>攻击力: {{ monster.attack }}</p>
                            <p>防御力: {{ monster.defense }}
                                {% if monster.defense_reduction %}
                                    (-{{ monster.defense_reduction }}%)
                                {% endif %}
                            </p>
                            <p>生命值: <span id="current-hp">{{ monster.hp }}</span>/{{ monster.hp }}</p>
                            <div class="tooltip-debuffs">
                                {% if monster.defense_reduction_duration %}
                                    <div class="tooltip-debuff-item">
                                        <span>防御力降低: {{ monster.defense_reduction }}% (剩余{{ monster.defense_reduction_duration }}回合)</span>
                                    </div>
                                {% endif %}
                            </div>
                        </div>
                    </div>
                </div>
                <div class="monster-hp">
                    <div class="hp-bar">
                        <div class="hp-fill" style="width: 100%"></div>
                        <span>HP: {{ monster.hp }}/{{ monster.hp }}</span>
                    </div>
                </div>
                <div class="monster-debuffs">
                    <!-- DEBUFF图标将在这里动态添加 -->
                </div>
            </div>
            {% endfor %}
        </div>
    </div>

    <!-- 在按钮之前添加调试信息 -->
    <div style="display:none" id="debug-info">
        Session ID: {{ session.id }}
        Floor ID: {{ session.current_floor }}
        Monster Count: {{ monsters|length }}
    </div>

    <!-- 修改按钮结构，添加调试属性 -->
    <div class="action-buttons">
        <button id="attack-btn" class="action-button">
            攻击
        </button>
        <div class="skill-buttons">
            {% for char_skill in character.characterskill_set.all %}
                {% if char_skill.skill.skill_type == 'ACTIVE' %}
                    <button class="skill-btn" 
                            data-skill-id="{{ char_skill.id }}"
                            data-skill-name="{{ char_skill.skill.name }}"
                            data-skill-type="{{ char_skill.skill.skill_type }}"
                            {% if char_skill.is_in_cooldown %}disabled{% endif %}>
                        {{ char_skill.skill.name }}
                        {% if char_skill.is_in_cooldown %}
                            (冷却中: {{ char_skill.remaining_cooldown }}回合)
                        {% endif %}
                    </button>
                {% endif %}
            {% endfor %}
        </div>
    </div>

    <!-- 战斗日志 -->
    <div class="battle-log">
        <ul id="battle-messages">
            <li>战斗开始！</li>
        </ul>
    </div>
</div>

<style>
    .game-container {
        max-width: 800px;
        margin: 0 auto;
        padding: 20px;
    }

    .floor-info {
        text-align: center;
        margin-bottom: 20px;
    }

    .character-status {
        display: flex;
        align-items: center;
        margin-bottom: 20px;
        padding: 10px;
        background: #f5f5f5;
        border-radius: 8px;
    }

    .character-avatar img {
        width: 80px;
        height: 80px;
        border-radius: 50%;
    }

    .status-bars {
        flex: 1;
        margin: 0 20px;
    }

    .hp-bar {
        background: #ddd;
        height: 20px;
        border-radius: 10px;
        overflow: hidden;
        position: relative;
    }

    .hp-fill {
        background: #ff4444;
        height: 100%;
        transition: width 0.3s ease;
    }

    .battle-area {
        height: 300px;
        background: #eee;
        margin: 20px 0;
        border-radius: 8px;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .monsters-container {
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 20px;
        margin: 20px 0;
        flex-wrap: wrap;  /* 如果怪物太多，允许换行 */
    }

    .monster-container {
        flex: 0 0 auto;  /* 防止怪物被拉伸 */
        width: 200px;    /* 固定宽度 */
        margin: 10px;
        text-align: center;
        background: rgba(255, 255, 255, 0.9);
        padding: 15px;
        border-radius: 10px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        position: relative;
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .monster-container.selected {
        border: 2px solid #4CAF50;
        transform: translateY(-5px);
        box-shadow: 0 5px 15px rgba(0,0,0,0.2);
    }

    .monster-container.dead {
        opacity: 0.5;
        pointer-events: none;
    }

    .target-indicator {
        position: absolute;
        top: -10px;
        right: -10px;
        background: #ff4444;
        color: white;
        padding: 5px 10px;
        border-radius: 15px;
        font-size: 12px;
        display: none;
        z-index: 10;
    }

    .monster-container.selectable .target-indicator {
        display: block;
    }

    .monster-image {
        cursor: pointer;
        transition: transform 0.2s;
    }

    .monster-image:hover {
        transform: scale(1.05);
    }

    .action-buttons {
        display: flex;
        gap: 10px;
        margin-bottom: 20px;
        flex-wrap: wrap;
        justify-content: center;
    }

    .action-button, .skill-btn {
        padding: 12px 24px;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        font-size: 16px;
        font-weight: bold;
        min-width: 120px;
        transition: all 0.3s ease;
    }

    .action-button {
        background: #ff4444;
        color: white;
    }

    .action-button:hover {
        background: #ff2222;
        transform: translateY(-2px);
    }

    .skill-btn {
        background: #4444ff;
        color: white;
        position: relative;
    }

    .skill-btn:hover:not(:disabled) {
        background: #2222ff;
        transform: translateY(-2px);
    }

    .skill-btn:disabled {
        background: #999;
        cursor: not-allowed;
        transform: none;
    }

    .battle-log {
        height: 200px;
        overflow-y: auto;
        padding: 15px;
        background: #f5f5f5;
        border-radius: 5px;
        margin-top: 20px;
        width: 100%;
        max-width: 800px;
        margin-left: auto;
        margin-right: auto;
    }

    .battle-log ul {
        list-style: none;
        padding: 0;
        margin: 0;
    }

    .battle-log li {
        margin: 8px 0;
        padding: 8px;
        border-bottom: 1px solid #ddd;
        line-height: 1.5;
        word-wrap: break-word;
    }

    .monster-container h3 {
        margin-bottom: 10px;
        color: #333;
    }
    
    .monster-stats {
        margin-top: 10px;
        text-align: center;
    }
    
    .monster-stats p {
        margin: 5px 0;
        color: #666;
    }

    .battle-log li.heal {
        color: #4CAF50;
    }

    .battle-log li.debuff {
        color: #9C27B0;
    }

    .battle-log li.critical {
        color: #f44336;
        font-weight: bold;
    }

    .battle-log li.miss {
        color: #9e9e9e;
        font-style: italic;
    }

    .monster-debuffs {
        position: absolute;
        top: 5px;
        left: 5px;
        display: flex;
        gap: 5px;
    }

    .debuff-icon {
        width: 24px;
        height: 24px;
        background: rgba(0,0,0,0.7);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 12px;
    }

    .monster-image-container {
        position: relative;
        display: inline-block;
        cursor: pointer;
    }

    .monster-tooltip {
        display: none;
        position: absolute;
        background: rgba(0, 0, 0, 0.9);
        color: white;
        padding: 10px;
        border-radius: 5px;
        width: 200px;
        z-index: 100;
        top: 50%;
        left: 100%;
        transform: translateY(-50%);
        margin-left: 10px;
    }

    .monster-image-container:hover .monster-tooltip {
        display: block;
    }

    .tooltip-content h4 {
        margin: 0 0 10px 0;
        color: #ffd700;
    }

    .tooltip-content p {
        margin: 5px 0;
        color: #fff;
    }

    .tooltip-debuffs {
        margin-top: 10px;
        border-top: 1px solid rgba(255, 255, 255, 0.2);
        padding-top: 5px;
    }

    .tooltip-debuff-item {
        display: flex;
        align-items: center;
        gap: 5px;
        margin: 3px 0;
        color: #ff6b6b;
    }

    .action-button.active {
        background: #666 !important;  /* 灰色背景 */
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0,0,0,0.2);
    }

    .skill-btn.active {
        background: #2222ff !important;
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0,0,0,0.2);
    }

    .monster-container {
        /* ... 其他样式保持不变 ... */
        transition: all 0.3s ease;
    }

    .monster-container.selectable {
        border: 2px dashed #ff4444;
        cursor: pointer;
    }

    .monster-container.selectable:hover {
        border: 2px solid #ff4444;
        transform: translateY(-5px);
        box-shadow: 0 5px 15px rgba(0,0,0,0.2);
    }

    @keyframes pulse {
        0% { transform: scale(1); }
        50% { transform: scale(1.02); }
        100% { transform: scale(1); }
    }
</style>

<script>
// 立即执行的调试代码
console.log('脚本开始执行');

// DOM加载检查
if (document.readyState === 'loading') {
    console.log('文档仍在加载中...');
} else {
    console.log('文档已经加载完成');
}

// 主要的游戏逻辑
const gameInit = function() {
    console.log('=== 战斗系统初始化开始 ===');
    
    // 获取DOM元素
    const attackBtn = document.getElementById('attack-btn');
    const battleMessages = document.getElementById('battle-messages');
    const playerHpFill = document.querySelector('.character-status .hp-fill');
    const monsterContainers = document.querySelectorAll('.monster-container');
    let currentAction = null;

    console.log('DOM元素状态:', {
        attackBtn: attackBtn ? '已找到' : '未找到',
        battleMessages: battleMessages ? '已找到' : '未找到',
        playerHpFill: playerHpFill ? '已找到' : '未找到',
        monsterContainers: `找到 ${monsterContainers.length} 个怪物`
    });

    // 更新玩家血条
    function updatePlayerHp(percentage) {
        playerHpFill.style.width = `${percentage}%`;
    }

    // 更新怪物血条
    function updateMonsterHp(monsterData) {
        for (const [monsterId, data] of Object.entries(monsterData)) {
            const monster = document.querySelector(`.monster-container[data-monster-id="${monsterId}"]`);
            if (monster) {
                const hpFill = monster.querySelector('.hp-fill');
                const hpText = monster.querySelector('.hp-bar span');
                const tooltipHp = monster.querySelector('.tooltip-content #current-hp');
                
                // 更新血条和血量文本
                hpFill.style.width = `${Math.max(0, data.hp_percentage)}%`;
                hpText.textContent = `HP: ${Math.max(0, data.current_hp)}/${data.max_hp}`;
                
                // 更新tooltip中的当前生命值
                if (tooltipHp) {
                    tooltipHp.textContent = Math.max(0, data.current_hp);
                }
                
                if (data.current_hp <= 0) {
                    monster.classList.add('dead');
                }
            }
        }
    }

    // 更新技能冷却状态的函数
    function updateSkillsStatus(skillsData) {
        if (!skillsData) return;
        
        for (const [skillId, data] of Object.entries(skillsData)) {
            const skillBtn = document.querySelector(`[data-skill-id="${skillId}"]`);
            if (skillBtn) {
                if (data.cooldown > 0) {
                    skillBtn.disabled = true;
                    skillBtn.textContent = `${data.name} (冷却中: ${data.cooldown}回合)`;
                } else {
                    skillBtn.disabled = false;
                    skillBtn.textContent = data.name;
                }
            }
        }
    }

    // 添加更新DEBUFF显示的函数
    function updateMonsterTooltip(monsterId, data) {
        const monsterContainer = document.querySelector(`.monster-container[data-monster-id="${monsterId}"]`);
        if (monsterContainer) {
            const defenseText = monsterContainer.querySelector('.tooltip-content p:nth-child(3)');
            const tooltipDebuffs = monsterContainer.querySelector('.tooltip-debuffs');
            
            // 更新防御力显示
            if (data.defense_reduction > 0) {
                defenseText.textContent = `防御力: ${data.defense} (-${data.defense_reduction}%)`;
            } else {
                defenseText.textContent = `防御力: ${data.defense}`;
            }
            
            // 更新debuff显示
            tooltipDebuffs.innerHTML = '';
            if (data.defense_reduction_duration > 0) {
                tooltipDebuffs.innerHTML = `
                    <div class="tooltip-debuff-item">
                        <span>防御力降低: ${data.defense_reduction}% (剩余${data.defense_reduction_duration}回合)</span>
                    </div>
                `;
            }
        }
    }

    // 在更新怪物状态的函数中调用
    function updateMonsterDebuffs(monsterData) {
        for (const [monsterId, data] of Object.entries(monsterData)) {
            const monster = document.querySelector(`.monster-container[data-monster-id="${monsterId}"]`);
            if (monster) {
                const debuffsContainer = monster.querySelector('.monster-debuffs');
                debuffsContainer.innerHTML = ''; // 清除现有DEBUFF
                
                if (data.defense_reduction && data.defense_reduction_duration > 0) {
                    const debuffIcon = document.createElement('div');
                    debuffIcon.className = 'debuff-icon';
                    debuffIcon.title = `防御力降低${data.defense_reduction}%\n剩余${data.defense_reduction_duration}回合`;
                    debuffIcon.textContent = '防↓';
                    debuffsContainer.appendChild(debuffIcon);
                }
                
                // 更新tooltip内容
                updateMonsterTooltip(monsterId, data);
            }
        }
    }

    // 修改更新战斗消息的部分
    function updateBattleMessage(messageText) {
        const message = document.createElement('li');
        message.innerHTML = messageText;  // 使用innerHTML而不是textContent
        battleMessages.appendChild(message);
        battleMessages.scrollTop = battleMessages.scrollHeight;
    }

    // 执行攻击
    function executeAttack(monsterId) {
        console.log('执行攻击:', monsterId);
        fetch('/game/battle/attack/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
            },
            body: JSON.stringify({
                monster_id: monsterId
            })
        })
        .then(response => response.json())
        .then(data => {
            console.log('攻击响应:', data);
            if (data.status === 'success') {
                // 更新战斗消息
                updateBattleMessage(data.message);
                
                // 更新所有怪物状态
                updateMonsterHp(data.monsters_data);
                updateMonsterDebuffs(data.monsters_data);
                
                // 更新玩家血量
                updatePlayerHp(data.player_hp_percentage);
                
                // 更新技能状态
                if (data.skills_data) {
                    updateSkillsStatus(data.skills_data);
                }
                
                // 检查是否需要进入下一层
                if (data.next_floor_url) {
                    setTimeout(() => {
                        window.location.href = data.next_floor_url;
                    }, 1000);  // 延迟1秒跳转，让玩家看到战斗结果
                }
                
                resetSelection();
            } else {
                console.error('攻击失败:', data.message);
            }
        })
        .catch(error => {
            console.error('攻击执行错误:', error);
            resetSelection();
        });
    }

    // 修改技能点击处理函数
    function handleSkillClick(skillBtn) {
        const skillId = skillBtn.dataset.skillId;
        const skillName = skillBtn.textContent.split(' ')[0];  // 获取技能名称
        
        // 重置所有选择状态
        resetSelection();
        
        // 对于回复技能，直接使用
        if (skillName === '回复') {
            executeSkill(skillId, null);
            return;
        }
        
        // 其他技能需要选择目标
        currentAction = skillId;
        document.querySelectorAll('.monster-container').forEach(container => {
            if (!container.classList.contains('dead')) {
                container.classList.add('selectable');
            }
        });
    }

    // 修改怪物点击处理函数
    function handleMonsterClick(monsterContainer) {
        const monsterId = monsterContainer.dataset.monsterId;
        
        // 如果没有选择任何动作，或者怪物已经死亡，则不处理
        if (!currentAction || monsterContainer.classList.contains('dead')) {
            return;
        }
        
        // 如果当前动作是技能ID
        if (currentAction !== 'attack') {
            const skillBtn = document.querySelector(`[data-skill-id="${currentAction}"]`);
            if (!skillBtn) return;
            
            const skillName = skillBtn.textContent.split(' ')[0];
            // 回复技能不应该到达这里
            if (skillName === '回复') {
                return;
            }
        }
        
        // 处理攻击或其他需要目标的技能
        if (currentAction === 'attack') {
            executeAttack(monsterId);
        } else {
            executeSkill(currentAction, monsterId);
        }
    }

    // 修改技能执行函数
    function executeSkill(skillId, targetId) {
        console.log('使用技能:', skillId, '目标:', targetId);
        fetch('/game/battle/skill/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
            },
            body: JSON.stringify({
                skill_id: skillId,
                target_id: targetId
            })
        })
        .then(response => response.json())
        .then(data => {
            console.log('技能响应:', data);
            if (data.status === 'success') {
                // 更新战斗消息
                updateBattleMessage(data.message);
                
                // 更新所有怪物状态
                updateMonsterHp(data.monsters_data);
                updateMonsterDebuffs(data.monsters_data);
                
                // 更新玩家血量
                updatePlayerHp(data.player_hp_percentage);
                
                // 更新技能状态
                if (data.skills_data) {
                    updateSkillsStatus(data.skills_data);
                }
                
                // 检查是否需要进入下一层
                if (data.next_floor_url) {
                    setTimeout(() => {
                        window.location.href = data.next_floor_url;
                    }, 1000);  // 延迟1秒跳转，让玩家看到战斗结果
                }
                
                resetSelection();
            } else {
                console.error('技能使用失败:', data.message);
            }
        })
        .catch(error => {
            console.error('技能请求错误:', error);
        });
    }

    // 重置选择状态
    function resetSelection() {
        console.log('重置选择状态');
        currentAction = null;
        document.querySelectorAll('.monster-container').forEach(container => {
            container.classList.remove('selectable');
        });
        document.querySelectorAll('.action-button, .skill-btn').forEach(btn => {
            btn.classList.remove('active');
        });
    }

    // 使怪物可选择
    function makeMonsterSelectable() {
        console.log('设置怪物可选择状态');
        document.querySelectorAll('.monster-container').forEach(container => {
            if (!container.classList.contains('dead')) {
                container.classList.add('selectable');
            }
        });
    }

    // 绑定攻击按钮事件
    if (attackBtn) {
        attackBtn.addEventListener('click', function(e) {
            console.log('攻击按钮被点击');
            e.preventDefault();
            
            if (currentAction === 'attack') {
                console.log('取消攻击选择');
                resetSelection();
                return;
            }

            currentAction = 'attack';
            console.log('设置攻击模式', currentAction);
            this.classList.add('active');
            makeMonsterSelectable();
        });
    }

    // 绑定技能按钮事件
    const skillButtons = document.querySelectorAll('.skill-btn');
    skillButtons.forEach(btn => {
        btn.addEventListener('click', function(e) {
            console.log('技能按钮被点击:', this.dataset.skillName);
            e.preventDefault();
            
            if (this.disabled) {
                console.log('技能在冷却中');
                return;
            }

            if (currentAction === this.dataset.skillId) {
                console.log('取消技能选择');
                resetSelection();
                return;
            }

            currentAction = this.dataset.skillId;
            this.classList.add('active');

            // 检查技能类型
            const skillType = this.dataset.skillType;
            if (skillType === 'HEAL') {
                console.log('使用回复技能');
                executeSkill(this.dataset.skillId, null);
                return;
            }

            // 其他技能需要选择目标
            makeMonsterSelectable();
        });
    });

    // 绑定怪物点击事件
    monsterContainers.forEach(container => {
        container.addEventListener('click', function(e) {
            console.log('怪物被点击，当前动作:', currentAction);
            e.preventDefault();
            
            if (!currentAction || this.classList.contains('dead') || !this.classList.contains('selectable')) {
                console.log('无效的怪物点击');
                return;
            }

            const monsterId = this.dataset.monsterId;
            console.log('处理怪物:', monsterId);

            if (currentAction === 'attack') {
                executeAttack(monsterId);
            } else {
                executeSkill(currentAction, monsterId);
            }
        });
    });
};

// 在 DOMContentLoaded 时初始化
document.addEventListener('DOMContentLoaded', gameInit);

// 错误处理
window.onerror = function(msg, url, line, col, error) {
    console.error('游戏错误:', {
        message: msg,
        url: url,
        line: line,
        col: col,
        error: error?.stack
    });
    return false;
};
</script>

<!-- 确保这个在 body 结束标签之前 -->
<script>
console.log('页面加载完成检查');
// 再次检查按钮
const finalCheck = document.getElementById('attack-btn');
console.log('最终检查攻击按钮:', finalCheck ? '存在' : '不存在');
</script>

<!-- 确保 CSRF Token 存在 -->
{% csrf_token %}
{% endblock %} 